<script lang="ts" setup>
import { ref, watch, defineEmits } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { useVbenModal } from '@vben/common-ui';

import { Button, message, DatePicker, Input } from 'ant-design-vue';

import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useVbenForm } from '#/adapter/form';
import {
  getProcessPurchaseInfo,
  addProcessPurchase,
  editProcessPurchase,
  getSupplyList,
  approvalProcessPurchase,
  againstProcessPurchase,
} from '#/api/backend/processPurchase';
import { getDict } from '#/api/common';

interface RowType {
  process_name?: string;
  goods_no?: string;
  color_name?: string;
  template_no?: string;
  delivery_date?: string;
  delivery_day?: string | number;
  price?: string | number;
  first?: string | number;
  second?: string | number;
  third?: string | number;
  fourth?: string | number;
  fifth?: string | number;
  sixth?: string | number;
  seventh?: string | number;
  eighth?: string | number;
  ninth?: string | number;
  tenth?: string | number;
  eleven?: string | number;
  twelve?: string | number;
  remark?: string;
  _X_ROW_KEY?: string;
}

const processPurchaseId = ref<number>();
const routerData = ref();
const formData = ref<any>({});
const dict = ref<any>({});
const submitLoading = ref(false);
const isDisabled = ref(true);
const emit = defineEmits(['fetchData']);

const keyword = ref<Record<string, any>>({
  supply_id: '',
});

/**
 * 获取数据详情
 */
const fetchData = async () => {
  const res = await getProcessPurchaseInfo(String(processPurchaseId.value));
  formApi.setValues(res.row);
  formData.value = { ...res.row };
  
  // 使用 setGridOptions 更新表格数据
  if (gridApi) {
    gridApi.setGridOptions({
      data: res.row.detail || [],
    });
  }

  Object.keys(keyword.value).forEach((key: string) => {
    if (res.row[key]) {
      keyword.value[key] = 'initValue:' + res.row[key];
    }
  });
};

/**
 * 获取供应商选项
 */
const supplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = '';
  let initValue = '';
  let initKey = 'id';

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '');
  } else {
    quick_search = keyword;
  }

  const { list } = await getSupplyList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
    supply_type: 2,
    Posted: 1,
  });

  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }));
};

/**
 * 初始化字典数据
 */
const init = async () => {
  const { select_list } = await getDict({
    keys: ['paymentMethod', 'paymentRule'],
    type: 2,
  });
  dict.value = select_list;

  formApi.updateSchema([
    {
      componentProps: {
        options: select_list.paymentMethod.map((item: any) => {
          const list = {
            label: item.name,
            value: item.value,
          };

          return list;
        }),
      },
      fieldName: 'fk_type',
    },
  ]);
  formApi.updateSchema([
    {
      componentProps: {
        options: select_list.paymentRule.map((item: any) => {
          const list = {
            label: item.name,
            value: item.name,
          };

          return list;
        }),
      },
      fieldName: 'fk_rule',
    },
  ]);
};

/**
 * 付款方式改变时的联动处理
 */
const fkChangeJoin = (value: any) => {
  const rules = dict.value.paymentRule.map((item: any) => ({
    label: item.name,
    value: item.name,
    disabled: item.value !== value,
  }));
  formApi.updateSchema([
    {
      fieldName: 'fk_rule',
      componentProps: {
        options: rules,
      },
    },
  ]);
  formApi.setValues({
    fk_rule: undefined,
  });
};

/**
 * 审核或反审操作
 */
const handleAgainstToApproval = async (type: string) => {
  modalApi.lock();
  try {
    if (type == 'approval') {
      await approvalProcessPurchase([String(processPurchaseId.value)]);
    } else {
      await againstProcessPurchase([String(processPurchaseId.value)]);
    }
    message.success('操作成功');
    emit('fetchData');
    modalApi.close();
  } finally {
    modalApi.lock(false);
  }
};

watch(isDisabled, (val) => {
  formApi.setState({ commonConfig: { disabled: val } });
});

const [Modal, modalApi] = useVbenModal({
  appendToMain: true,
  fullscreen: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      routerData.value = modalApi.getData<Record<string, any>>();
      processPurchaseId.value = 0;
      formApi.setValues({});
      gridApi.setGridOptions({
        data: [],
      });
      Object.keys(keyword.value).forEach((key) => {
        keyword.value[key] = '';
      });
      init();

      if (routerData.value?.info?.id) {
        processPurchaseId.value = routerData.value?.info?.id;
      }

      if (processPurchaseId.value) {
        fetchData();
        isDisabled.value = true;
      } else {
        isDisabled.value = false;
      }
    }
  },
});

/**
 * 表格配置
 */
const gridOptions: VxeGridProps<RowType> = {
  pagerConfig: {
    enabled: false,
  },
  columns: [
    { type: 'seq', width: 90, title: '编号' },
    { field: 'process_name', title: '工序名称', width: 150 },
    { field: 'goods_no', title: '货号', width: 150 },
    { field: 'color_name', title: '颜色', width: 100 },
    { field: 'template_no', title: '简码', width: 150 },
    {
      field: 'delivery_date',
      title: '交期',
      width: 150,
      editRender: {},
      slots: { edit: 'delivery_date_edit' },
    },
    {
      field: 'delivery_day',
      title: '生产周期(天)',
      width: 120,
      editRender: {},
      slots: { edit: 'delivery_day_edit' },
    },
    {
      field: 'price',
      title: '单价',
      width: 100,
      editRender: {},
      slots: { edit: 'price_edit' },
    },
    {
      field: 'first',
      title: '28/46/165/37/S',
      width: 100,
      editRender: {},
      slots: { edit: 'first_edit' },
    },
    {
      field: 'second',
      title: '29/48/170/38/M',
      width: 100,
      editRender: {},
      slots: { edit: 'second_edit' },
    },
    {
      field: 'third',
      title: '30/50/175/39/L',
      width: 100,
      editRender: {},
      slots: { edit: 'third_edit' },
    },
    {
      field: 'fourth',
      title: '31/52/180/40/XL',
      width: 100,
      editRender: {},
      slots: { edit: 'fourth_edit' },
    },
    {
      field: 'fifth',
      title: '32/54/185/41/2XL',
      width: 100,
      editRender: {},
      slots: { edit: 'fifth_edit' },
    },
    {
      field: 'sixth',
      title: '33/56/190/42/3XL',
      width: 100,
      editRender: {},
      slots: { edit: 'sixth_edit' },
    },
    {
      field: 'seventh',
      title: '34/58/195/43/4XL',
      width: 100,
      editRender: {},
      slots: { edit: 'seventh_edit' },
    },
    {
      field: 'eighth',
      title: '35/5XL',
      width: 100,
      editRender: {},
      slots: { edit: 'eighth_edit' },
    },
    {
      field: 'ninth',
      title: '36/6XL',
      width: 100,
      editRender: {},
      slots: { edit: 'ninth_edit' },
    },
    {
      field: 'tenth',
      title: '38/7XL',
      width: 100,
      editRender: {},
      slots: { edit: 'tenth_edit' },
    },
    {
      field: 'eleven',
      title: '40',
      width: 100,
      editRender: {},
      slots: { edit: 'eleven_edit' },
    },
    {
      field: 'twelve',
      title: '42/00均码',
      width: 100,
      editRender: {},
      slots: { edit: 'twelve_edit' },
    },
    {
      field: 'remark',
      title: '备注',
      width: 190,
      editRender: {},
      slots: { edit: 'remark_edit' },
    },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 80,
    },
  ],
  exportConfig: {},
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
  height: '500px',
  keepSource: false,
  data: [],
  showOverflow: false,
};

/**
 * 切换编辑状态
 */
const handleUpdate = async () => {
  isDisabled.value = !isDisabled.value;
};

/**
 * 删除行数据
 */
const handleRowDelete = async (row: RowType) => {
  if (gridApi) {
    const currentData = gridApi.grid.getData();
    const index = currentData.findIndex(
      (item: any) => item._X_ROW_KEY === row._X_ROW_KEY,
    );

    if (index !== -1) {
      currentData.splice(index, 1);
      gridApi.setGridOptions({
        data: currentData,
      });
    }
  }
};

/**
 * 保存表单（防抖）
 */
const handleSubmit = useDebounceFn(async () => {
  await onSubmit();
}, 300);

/**
 * 表单提交
 */
async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    submitLoading.value = true;
    try {
      let saveData = await formApi.getValues();
      if (gridApi) {
        const tableData = gridApi.grid.getData();
        saveData.detail = tableData;
      }
      if (processPurchaseId.value) {
        await editProcessPurchase({ ...saveData, id: processPurchaseId.value });
      } else {
        await addProcessPurchase(saveData);
      }
      message.success('保存成功');
      emit('fetchData');
      modalApi.close();
    } finally {
      submitLoading.value = false;
    }
  }
}

/**
 * 关闭弹窗
 */
const handleClose = async () => {
  modalApi.close();
};

const [Form, formApi] = useVbenForm({
  commonConfig: {
    disabled: isDisabled.value,
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'sn',
      label: '单号',
      componentProps: {
        disabled: true,
        placeholder: '自动生成',
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'supply_id',
      label: '供应商',
      rules: 'required',
      componentProps: () => ({
        api: supplyOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.supply_id = value;
        }, 300),
        params: {
          keyword: keyword.value.supply_id || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        maxTagCount: 'responsive',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.supply_id = '';
        },
      }),
    },
    {
      component: 'Select',
      fieldName: 'fk_type',
      label: '付款方式',
      rules: 'required',
      componentProps: {
        placeholder: '请选择结算方式',
        onChange: (value: any) => {
          fkChangeJoin(value);
        },
      },
    },
    {
      component: 'Select',
      fieldName: 'fk_rule',
      label: '付款规则',
      rules: 'required',
      componentProps: () => ({
        placeholder: '请选择结算规则',
      }),
    },
    {
      component: 'Textarea',
      fieldName: 'remark',
      label: '备注',
      componentProps: {
        placeholder: '请输入备注',
      },
    },
  ],
  wrapperClass: 'grid grid-cols-4',
});

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
});
</script>
<template>
  <Modal title="工序采购单">
    <div class="p-4">
      <Form />
      <div class="my-2 flex items-center justify-between">
        <h3 class="text-lg font-medium">明细列表</h3>
      </div>
      <Grid>
        <template #operation="{ row }">
          <Button
            :disabled="isDisabled"
            danger
            size="small"
            @click="handleRowDelete(row)"
            >删除</Button
          >
        </template>
        <template #delivery_date_edit="{ row }">
          <DatePicker
            :disabled="isDisabled"
            type="date"
            clearable="true"
            placeholder="请选择交期"
            v-model:value="row.delivery_date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placement="bottomLeft"
            :get-popup-container="
              (triggerNode) =>
                (triggerNode.parentNode as HTMLElement) || triggerNode
            "
          />
        </template>
        <template #delivery_day_edit="{ row }">
          <Input v-model:value="row.delivery_day" :disabled="isDisabled" />
        </template>
        <template #price_edit="{ row }">
          <Input v-model:value="row.price" :disabled="isDisabled" />
        </template>
        <template #first_edit="{ row }">
          <Input v-model:value="row.first" :disabled="isDisabled" />
        </template>
        <template #second_edit="{ row }">
          <Input v-model:value="row.second" :disabled="isDisabled" />
        </template>
        <template #third_edit="{ row }">
          <Input v-model:value="row.third" :disabled="isDisabled" />
        </template>
        <template #fourth_edit="{ row }">
          <Input v-model:value="row.fourth" :disabled="isDisabled" />
        </template>
        <template #fifth_edit="{ row }">
          <Input v-model:value="row.fifth" :disabled="isDisabled" />
        </template>
        <template #sixth_edit="{ row }">
          <Input v-model:value="row.sixth" :disabled="isDisabled" />
        </template>
        <template #seventh_edit="{ row }">
          <Input v-model:value="row.seventh" :disabled="isDisabled" />
        </template>
        <template #eighth_edit="{ row }">
          <Input v-model:value="row.eighth" :disabled="isDisabled" />
        </template>
        <template #ninth_edit="{ row }">
          <Input v-model:value="row.ninth" :disabled="isDisabled" />
        </template>
        <template #tenth_edit="{ row }">
          <Input v-model:value="row.tenth" :disabled="isDisabled" />
        </template>
        <template #eleven_edit="{ row }">
          <Input v-model:value="row.eleven" :disabled="isDisabled" />
        </template>
        <template #twelve_edit="{ row }">
          <Input v-model:value="row.twelve" :disabled="isDisabled" />
        </template>
        <template #remark_edit="{ row }">
          <Input v-model:value="row.remark" :disabled="isDisabled" />
        </template>
      </Grid>
    </div>
    <template #prepend-footer>
      <Button @click="handleClose()">取消</Button>
      <template v-if="processPurchaseId">
        <Button
          class="bg-[#f56c6c] text-white"
          @click="
            handleAgainstToApproval(formData.state >= 20 ? 'against' : 'approval')
          "
        >
          {{ formData.state >= 20 ? '反审' : '审核' }}
        </Button>
        <Button
          v-if="formData.state < 20 && isDisabled"
          class="bg-[#f0a62f] text-[#fff]"
          @click="handleUpdate()"
          >修改</Button
        >
      </template>
      <Button
        v-if="!isDisabled || !processPurchaseId"
        type="primary"
        :loading="submitLoading"
        :disabled="submitLoading"
        @click="handleSubmit"
        >保存</Button
      >
    </template>
  </Modal>
</template>

<style lang="scss" scoped>
</style>

